import { WebSocketServer } from "ws";
import { networkInterfaces } from "os";

//用户连接
let clients = [];
//房间集合
let roomIdList = [];
//聊天记录集合
let messageList = [];

function getLocalIP() {
  const nets = networkInterfaces();
  for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
      // 排除IPv6和内部IP（如环回地址127.0.0.1）
      if (net.family === "IPv4" && !net.internal) {
        return net.address;
      }
    }
  }
  return "127.0.0.1"; // 如果没有找到，返回本地回环地址
}
let ip = getLocalIP();

let ws = new WebSocketServer({ host: ip, port: 3000 });

export const listen = () => {
  ws.on("connection", function connection(ws, request, client) {
    let url = request.headers.origin + request.url;
    let userId = getParam(url, "userId");
    console.log("客户端已连接--用户Id", userId);
    if (userId) {
      clients.forEach((e, i) => {
        if (e["userId"] == userId) {
          //去掉之前的连接实例，更新新的
          clients.splice(i, 1);
        }
      });
      clients.push({ userId, ws: ws });
    }

    ws.on("message", function message(data) {
      console.log("received: %s", data);
      try {
        let objMessage = JSON.parse(`${data}`);
        let { userId, message, roomId, roomName, operate, created } =
          objMessage;

        //operate 0:创建房间 1:加入房间 2:聊天 3:删除房间 4:关闭连接
        if (userId && operate == 0) {
          let index = roomIdList.findIndex((t) => t.roomId == roomId);
          if (index > -1) {
            let data = {
              userId,
              message: "房间已存在",
              operate,
            };
            ws.send(JSON.stringify(data));
          } else {
            let data = {
              roomId,
              roomName,
              userIdList: [{ userId, ws: ws }],
              message: "创建成功",
              userId,
              operate: 0,
              created,
            };
            let user = {
              roomId,
              roomName,
              userIdList: [{ userId, ws: ws }],
              created,
            };
            roomIdList.push(user);
            ws.send(JSON.stringify(data));
          }
        }

        if (userId && operate == 1) {
          let index = roomIdList.findIndex((t) => t.roomId * 1 == roomId * 1);
          //判断加入的房间是否存在
          if (index > -1) {
            let type = false;
            roomIdList[index].userIdList.forEach((u) => {
              if (u["userId"] == userId) {
                type = true;
              }
            });
            //判断该用户是否在群聊中
            if (!type) {
              roomIdList[index].userIdList.push({ userId, ws: ws });
              let data = {
                userId,
                roomId,
                roomName: roomIdList[index].roomName,
                operate: 1,
                message: "用户" + userId + "加入群聊",
                isExist: true,
                in: true,
              };
              roomIdList[index].userIdList.forEach((e) => {
                if (e["userId"] != userId) {
                  e["ws"].send(JSON.stringify(data));
                } else {
                  let data = {
                    userId,
                    roomId,
                    roomName: roomIdList[index].roomName,
                    operate: 1,
                    message: "已成功加入群聊",
                    isExist: true,
                  };
                  e["ws"].send(JSON.stringify(data));
                }
              });
            } else {
              roomIdList[index].userIdList.forEach((e) => {
                if (e["userId"] == userId) {
                  let data = {
                    userId,
                    roomId,
                    roomName: roomIdList[index].roomName,
                    operate: 1,
                    message: "你已在群聊中，无需重复加入",
                    isExist: false,
                  };
                  //刷新后更新ws实例
                  clients.forEach((c) => {
                    if (c["userId"] == userId) {
                      c["ws"].send(JSON.stringify(data));
                    }
                  });
                }
              });
            }
          } else {
            let data = {
              userId,
              roomId,
              operate,
              message: "房间不存在",
              isExist: false,
              in: true,
            };
            ws.send(JSON.stringify(data));
          }
        }

        if (userId && operate == 2) {
          let data = {
            operate,
            userId,
            message,
            in: false,
          };

          roomIdList.forEach((r) => {
            if (r["roomId"] == roomId) {
              r.userIdList.forEach((u) => {
                if (u["userId"] != userId) {
                  u["ws"].send(JSON.stringify(data));
                }
              });
            }
          });
        }

        if (userId && operate == 3) {
          roomIdList.forEach((r) => {
            if (r["roomId"] == roomId && userId == created) {
              r.userIdList.forEach((u) => {
                if (u["userId"] == userId) {
                  let data = {
                    operate: 3,
                    userId,
                    message: "删除成功",
                    roomId,
                    delStauts: 0,
                  };
                  u["ws"].send(JSON.stringify(data));
                  roomIdList.splice(index, 1);
                }
              });
            } else {
              r.userIdList.forEach((u) => {
                if (u["userId"] == userId) {
                  let data = {
                    operate: 3,
                    userId,
                    message: "您不是房间创立者，无权限删除房间。",
                    roomId,
                    delStauts: 1,
                  };
                  u["ws"].send(JSON.stringify(data));
                }
              });
            }
          });
        }
      } catch (error) {
        ws.send(JSON.stringify({ message: error.message }));
      }
    });

    ws.on("open", (msg) => {
      console.log("客户端已连接", msg);
    });

    ws.on("close", function close(err) {
      console.log("客户端断开连接", err);
    });

    ws.on("error", (err) => {
      console.log("异常", err);
    });
  });
};

const getParam = (url, param) =>
  new URLSearchParams(new URL(url).search).get(param);

console.log(`服务器正在运行:ws://${ip}:3000"`);
